package com.epam.web_project.bank.command.customer_commands;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.epam.web_project.bank.command.Command;
import com.epam.web_project.bank.dao.customer_dao.CustomerDAO;
import com.epam.web_project.bank.dao.factory.MySQLDAOFactory;
import com.epam.web_project.bank.db.ConnectionPool;
import com.epam.web_project.bank.entity.Customer;
import com.epam.web_project.bank.util.AppPropertiesLoader;
import com.epam.web_project.bank.util.PasswordEncoder;

public class ChangePasswordCommand implements Command {

	//password recovery - changing password
	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		AppPropertiesLoader propLoader = AppPropertiesLoader.getInstance();
		HttpSession session = request.getSession();
		if (!session.isNew()) {
			Customer customer = (Customer)session.getAttribute("customerTemp");
			String plainPassword = request.getParameter("password");
			String passwordHash = PasswordEncoder.sha2Encode(plainPassword);
			MySQLDAOFactory daoFactory = new MySQLDAOFactory();
			daoFactory.setConnectionPool(ConnectionPool.getInstance());
			CustomerDAO customerDAO = daoFactory.getCustomerDAO();
			if (customerDAO.changePassword(customer, passwordHash)) {
				request.setAttribute("message",
						propLoader.getProperty("CHANGING_PASSWORD_SUCCESS"));
			} else {
				request.setAttribute("message",
						propLoader.getProperty("PASSWORD_CHANGE_FAIL"));
			}
		} else {
			request.setAttribute("message",
					propLoader.getProperty("NO_CUSTOMER_ID"));
		}
		session.invalidate();
		return propLoader.getProperty("login_page");
	}

}
